package reflectionAndAnnotation.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/24 11:54
 */
public class Construction {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //通过反射获得class对象
        Class<?> aClass = Class.forName("reflectionAndAnnotation.reflection.model.User");

        //获得对象的构造方法(所有的公共方法)
        Constructor<?>[] constructors = aClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println();
        //全部方法
        Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors();
        for (Constructor<?> constructor : declaredConstructors) {
            System.out.println(constructor);
        }
        System.out.println();

        //获得对象的指定方法 (传递参数类型的class对象) 单个公共
        Constructor<?> constructor = aClass.getConstructor(int.class, String.class, int.class);
        System.out.println(constructor);
        System.out.println();
        //单个所有
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(int.class);
        System.out.println(declaredConstructor);
        System.out.println();

        //创建User对象(公共的)
        Object obj = constructor.newInstance(0, "周", 20);
        System.out.println(obj);
        //私有的
        //暴力反射（可创建私有对象）
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance(50);
        System.out.println(o);

    }
}
